package com.enation.app.javashop.consumer.shop.trade.consumer;

import com.enation.app.javashop.consumer.core.event.MemberRegisterEvent;
import com.enation.app.javashop.consumer.core.event.OrderStatusChangeEvent;
import com.enation.app.javashop.consumer.core.event.RefundStatusChangeEvent;
import com.enation.app.javashop.consumer.core.event.TradeIntoDbEvent;
import com.enation.app.javashop.consumer.core.receiver.RefundStatusChangeReceiver;
import com.enation.app.javashop.core.base.message.MemberRegisterMsg;
import com.enation.app.javashop.core.base.message.OrderStatusChangeMsg;
import com.enation.app.javashop.core.base.message.RefundChangeMsg;
import com.enation.app.javashop.core.base.model.vo.SmsSendVO;
import com.enation.app.javashop.core.client.member.MemberClient;
import com.enation.app.javashop.core.client.system.SmsClient;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dos.MemberCoupon;
import com.enation.app.javashop.core.member.service.MemberCouponManager;
import com.enation.app.javashop.core.promotion.coupon.model.dos.CouponDO;
import com.enation.app.javashop.core.promotion.coupon.model.dos.CouponTypeEnum;
import com.enation.app.javashop.core.promotion.coupon.service.CouponManager;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.trade.cart.model.vo.CouponVO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderMetaKeyEnum;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.model.vo.TradeVO;
import com.enation.app.javashop.core.trade.order.service.OrderMetaManager;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.util.CurrencyUtil;
import com.enation.app.javashop.framework.util.JsonUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 确认收款发放促销活动赠送优惠券
 * @author Snow create in 2018/5/22
 * @version v2.0
 * @since v7.0.0
 */
@Component
public class CouponConsumer implements OrderStatusChangeEvent,TradeIntoDbEvent, MemberRegisterEvent {

    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private OrderMetaManager orderMetaManager;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private CouponManager couponManager;

    @Autowired
    private MemberCouponManager memberCouponManager;

    @Autowired
    private SmsClient smsClient;

    @Autowired
    private ShopManager shopManager;

    @Override
    public void orderChange(OrderStatusChangeMsg orderMessage) {

        if ((orderMessage.getNewStatus().name()).equals(OrderStatusEnum.PAID_OFF.name())) {

            //读取已发放的优惠券json
            String itemJson = this.orderMetaManager.getMetaValue(orderMessage.getOrderDO().getSn(), OrderMetaKeyEnum.COUPON);
            List<CouponVO> couponList = JsonUtil.jsonToList(itemJson,CouponVO.class);
            if (couponList != null && couponList.size() > 0) {

                // 循环发放的优惠券
                for (CouponVO couponVO : couponList) {
                    CouponDO couponDO = this.couponManager.getModel(couponVO.getCouponId());
                    //优惠券可领取数量不足时,不赠送优惠券
                    if(CurrencyUtil.sub(couponDO.getCreateNum(),couponDO.getReceivedNum()) <= 0){
                        continue;
                    }
                    this.memberClient.receiveBonus(orderMessage.getOrderDO().getMemberId(),couponVO.getCouponId());
                }
            }
        }

        if (orderMessage.getNewStatus().equals(OrderStatusEnum.CANCELLED)) {
            logger.info("【订单取消，退回优惠券】:"+orderMessage.getOrderDO().getSn());
            this.memberCouponManager.retrieveCoupon(orderMessage.getOrderDO().getSn());
        }
    }


    @Override
    public void onTradeIntoDb(TradeVO tradeVO) {
        try{
            //优惠券状态提前变更
            //将使用过的优惠券变为已使用
            List<CouponVO> useCoupons = tradeVO.getCouponList();
            String orderSn = tradeVO.getOrderList().get(0).getSn();
            if(useCoupons != null){
                for(CouponVO couponVO:useCoupons){
                    this.memberClient.usedCoupon(couponVO.getMemberCouponId(),orderSn);
                    MemberCoupon memberCoupon = this.memberClient.getModel(tradeVO.getMemberId(),couponVO.getMemberCouponId());
                    //修改店铺已经使用优惠券数量
                    this.couponManager.addUsedNum(memberCoupon.getCouponId());
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("更改优惠券的状态完成");
            }

        }catch (Exception e){
            logger.error("更改优惠券的状态出错",e);
        }
    }

    /**
     * 新用户注册发送优惠券
     * @param memberRegisterMsg
     */
    @Override
    public void memberRegister(MemberRegisterMsg memberRegisterMsg) {
//        Member member = memberRegisterMsg.getMember();
//        try{
//            // 根据用户所在城市定位店铺优惠券
//            Integer sellerId=null;
//            Integer shopId = shopManager.getShopByCity(member.getCity());
//            if(shopId!=null && shopId!=0){
//                sellerId=shopId;
//            }
//
//            // 从数据库中获取优惠券
//            List<CouponDO> couponList = this.couponManager.getList(sellerId, CouponTypeEnum.NEW_REG.value());
//
//            if(CollectionUtils.isEmpty(couponList)){
//                return;
//            }
//
//            // 发放优惠券
//            StringBuilder contentBuilder=new StringBuilder("【智溢商城 新用户发券】：您的");
//            boolean hasCoupon=false;
//            for (CouponDO couponDO : couponList) {
//                // 校验已领取总数
//                if (couponDO.getReceivedNum() >= couponDO.getCreateNum()) {
//                    continue;
//                }
//                // 发券(按照额度 领完为止)
//                Integer limitNum = couponDO.getLimitNum();
//                for (int i = 0; i < limitNum; i++) {
//                    this.memberCouponManager.receiveBonus(new MemberCoupon(member.getMemberId(),couponDO.getCouponId()));
//                }
//                hasCoupon=true;
//                contentBuilder.append(couponDO.getTitle()+couponDO.getLimitNum()+"张,");
//            }
//            contentBuilder.append("已到账，记得及时抢购哦~");
//            // 通知用户
//            if(hasCoupon){
//                SmsSendVO smsSendVO = new SmsSendVO();
//                smsSendVO.setMobile(member.getMobile());
//                smsSendVO.setContent(contentBuilder.toString());
//                this.smsClient.send(smsSendVO);
//            }
//        }catch (Exception e){
//            logger.error("新用户注册发送优惠券",e);
//        }
    }
}
